import React from 'react'
import {observer} from 'mobx-react'
import {Button, Form, Input, Radio, Selector, Space, Toast} from 'antd-mobile'
import http from 'libs/http'
import styles from './index.module.css'
import store from './store'
import Agreement from './Agreement'
import PaySuccess from './success'
import Payment from './Payment'

@observer
class Register extends React.Component {
  state = {
    loading: false,
    showClassInfo: false, // 控制是否显示班级信息
  }

  // 学员类型选项
  studentTypes = [
    {label: '文化生', value: '文化生'},
    {label: '艺术生', value: '艺术生'},
    {label: '体育生', value: '体育生'}
  ]

  // 上课类型选项
  classTypes = [
    {label: '校内上课', value: 'in_school'},
    {label: '校外上课', value: 'out_school'}
  ]

  // 年级选项
  gradeOptions = [
    {label: '高一', value: 'grade_1'},
    {label: '高二', value: 'grade_2'},
    {label: '高三', value: 'grade_3'}
  ]

  // 生成班级选项 1-30班
  getClassOptions = () => {
    return Array.from({length: 30}, (_, i) => ({
      label: `${i + 1}班`,
      value: `class_${i + 1}`
    }))
  }

  componentDidMount() {
    this.checkWxEnvironment()
    this.initializeFromUrl()

    // 检查是否需要返回到支付页面
    this.checkReturnToPayment()

    // 恢复之前保存的状态
    this.restoreState()
  }

  // 检查是否在微信环境中
  checkWxEnvironment = () => {
    const isWxClient = /MicroMessenger/i.test(navigator.userAgent)
    if (!isWxClient) {
      Toast.show({
        content: '请使用微信打开',
        position: 'center',
        duration: 3000
      })
    }

  }

  initializeFromUrl = () => {
    const params = new URLSearchParams(window.location.search)

    // 获取课程信息
    const courseIds = params.get('courseIds')
    const code = params.get('code')
    if (courseIds) {
      http.get('/api/app/course/', {params: {ids: courseIds}})
        .then(res => {
          store.schoolName = res[0].category_info.school
          store.examYear = res[0].year
          store.setCourseInfo(res)
        }, () => Toast.show({content: '获取课程信息失败'}))
    }
    if (code) {
      http.get('/api/app/wx/oauth/callback/', {params: {code}})
        .then(res => {
          store.setOpenid(res.openid)
          sessionStorage.setItem('openid', res.openid)
        }, () => Toast.show({content: '获取openid失败'}))
    }
  }

  handleFormSubmit = (values) => {
    console.log('handleFormSubmit')
    store.formData = {...store.formData, ...values}
    store.currentStep = 'agreement'
  }

  handleAgreementBack = () => {
    store.currentStep = 'form'
  }

  handleAgreementSubmit = async () => {
    this.setState({loading: true})
    console.log('handleAgreementSubmit')

    // 如果 courseInfo 为空数组，显示提示
    if (store.courseInfo.length === 0) {
      Toast.show({
        content: '没有选择课程，请返回重新选择',
        position: 'top'
      })
      this.setState({loading: false})
      return
    }

    store.currentStep = 'payment'
    this.setState({loading: false})
  }

  handleClassTypeChange = (value) => {
    this.setState({showClassInfo: value === 'in_school'})
  }

  // 恢复之前保存的状态
  restoreState = () => {
    try {
      // 恢复表单数据
      const formData = sessionStorage.getItem('formData')
      if (formData) {
        store.formData = JSON.parse(formData)
        console.log('恢复表单数据:', store.formData)
      }

      // 恢复课程信息
      const courseInfo = sessionStorage.getItem('courseInfo')
      if (courseInfo) {
        store.setCourseInfo(JSON.parse(courseInfo))
        console.log('恢复课程信息:', store.courseInfo)
      }

      // 恢复学校信息
      const schoolName = sessionStorage.getItem('schoolName')
      if (schoolName) {
        store.schoolName = schoolName
      }

      // 恢复考试年份
      const examYear = sessionStorage.getItem('examYear')
      if (examYear) {
        store.examYear = examYear
      }

      // 恢复课程总价
      const courseTotalPrice = sessionStorage.getItem('courseTotalPrice')
      if (courseTotalPrice) {
        store.courseTotalPrice = parseFloat(courseTotalPrice)
      }
    } catch (error) {
      console.error('恢复状态失败:', error)
    }
  }

  // 检查是否需要返回到支付页面
  checkReturnToPayment = () => {
    const returnUrl = sessionStorage.getItem('payment_return_url')
    if (returnUrl) {
      console.log('检测到需要返回到支付页面:', returnUrl)

      // 如果已经获取到openid，则返回到支付页面
      if (store.openid) {
        console.log('已获取到openid，准备返回支付页面')

        // 清除返回URL
        sessionStorage.removeItem('payment_return_url')

        // 设置当前步骤为支付页面
        store.currentStep = 'payment'
      }
    }
  }


  renderForm() {
    return (
      <div className={styles.container}>
        <div className={styles.header}>
          <div className={styles.schoolCard}>
            <div className={styles.schoolName}>
              就读学校：{store.schoolName}
            </div>
            <div className={styles.examYear}>
              应届高考年份：{store.examYear}
            </div>
          </div>
        </div>

        <div className={styles.formContainer}>
          <Form
            layout="vertical"
            onFinish={this.handleFormSubmit}
            initialValues={store.formData}
            footer={
              <Button
                block
                type="submit"
                color="primary"
                loading={this.state.loading}
                className={styles.submitBtn}>
                提交
              </Button>
            }>
            <Form.Item
              name="name"
              label="学生姓名"
              rules={[{required: true, message: '请输入学生姓名'}]}>
              <Input placeholder="请输入学生姓名"/>
            </Form.Item>

            <Form.Item
              name="id_card"
              label="学生身份证号"
              rules={[{required: true, message: '请输入身份证号'}]}>
              <Input placeholder="请输入身份证号"/>
            </Form.Item>

            <Form.Item
              name="parent_name"
              label="家长姓名"
              rules={[{required: true, message: '请输入家长姓名'}]}>
              <Input placeholder="请输入家长姓名"/>
            </Form.Item>

            <Form.Item
              name="parent_phone"
              label="家长手机号"
              rules={[{required: true, message: '请输入家长手机号'}]}>
              <Input placeholder="该手机号码将作为唯一查询使用" type="tel"/>
            </Form.Item>

            <Form.Item
              name="student_type"
              label="学员类型"
              rules={[{required: true, message: '请选择学员类型'}]}>
              <Radio.Group>
                <Space style={{
                  width: '100%',
                  justifyContent: 'space-between',
                  '--gap': '8px',
                }}>
                  {this.studentTypes.map(type => (
                    <Radio
                      key={type.value}
                      value={type.value}
                      style={{
                        padding: '8px 12px',
                        '--font-size': '14px',
                        '--gap': '6px',
                      }}>
                      {type.label}
                    </Radio>
                  ))}
                </Space>
              </Radio.Group>
            </Form.Item>

            <Form.Item
              name="class_type"
              label="上课类型"
              rules={[{required: true, message: '请选择上课类型'}]}>
              <Radio.Group onChange={(val) => this.handleClassTypeChange(val)}>
                <Space style={{
                  width: '100%',
                  justifyContent: 'space-between',
                  '--gap': '8px',
                }}>
                  {this.classTypes.map(type => (
                    <Radio
                      key={type.value}
                      value={type.value}
                      style={{
                        padding: '8px 12px',
                        '--font-size': '14px',
                        '--gap': '6px',
                      }}>
                      {type.label}
                    </Radio>
                  ))}
                </Space>
              </Radio.Group>
            </Form.Item>

            {this.state.showClassInfo && (
              <>
                <Form.Item
                  name="grade"
                  label="年级"
                  rules={[{required: true, message: '请选择年级'}]}>
                  <Radio.Group>
                    <Space style={{
                      width: '100%',
                      justifyContent: 'space-between',
                      '--gap': '8px',
                    }}>
                      {this.gradeOptions.map(grade => (
                        <Radio
                          key={grade.value}
                          value={grade.value}
                          style={{
                            padding: '8px 12px',
                            '--font-size': '14px',
                            '--gap': '6px',
                          }}>
                          {grade.label}
                        </Radio>
                      ))}
                    </Space>
                  </Radio.Group>
                </Form.Item>

                <Form.Item
                  name="class_number"
                  label="班级"
                  rules={[{required: true, message: '请选择班级'}]}>
                  <Selector
                    columns={3}
                    options={this.getClassOptions()}
                    style={{
                      '--border-radius': '4px',
                    }}
                  />
                </Form.Item>
              </>
            )}
          </Form>
        </div>

        <div className={styles.agreement}>
          <p>上述内容将录入电子合同，请仔细核对</p>
        </div>
      </div>
    )
  }

  render() {
    const {currentStep} = store

    switch (currentStep) {
      case 'form':
        return this.renderForm()
      case 'agreement':
        return (
          <Agreement
            onBack={this.handleAgreementBack}
            onSubmit={this.handleAgreementSubmit}
          />
        )
      case 'payment':
        return <Payment/>
      case 'success':
        return <PaySuccess/>
      default:
        return this.renderForm()
    }
  }
}

export default Register